//
//  UserView.m
//  TwitterFon
//
//  Created by kaz on 11/16/08.
//  Copyright 2008 naan studio. All rights reserved.
//

#import "GuaziAppDelegate.h"
#import "UserView.h"
#import "QuartzUtils.h"
#import "ColorUtils.h"
#import "UserService.h"

#define kMessageUserProtected @"This user has protected their updates."
#define kMessageDetail        @"You need to send a request before you can start following this person."

#define kRemoveButtonAnim @"removeButtonAnimation"
#define kFollowButtonAnim @"followButtonAnimation"
#define kMessageFlashAnim @"messageFlashAnimation"

#define kFollowButtonTag 101
#define kSilenceButtonTag 102
#define kCancelButtonTag 103

@interface NSObject (UserViewDelegate)
- (void)requestFriendship:(BOOL)createOrDestroy;
- (void) showFollowButtons;
@end


@implementation UserView

@synthesize user;
@synthesize profileImage;


- (id)initWithFrame:(CGRect)frame 
{
    self = [super initWithFrame:frame];
    
	editButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	editButton.frame = CGRectMake(230, 18, 80, 30);
	[editButton setTitle:@"编辑" forState:UIControlStateNormal];
	[self addSubview:editButton];
    
    followButton = [UIButton buttonWithType:UIButtonTypeCustom];
    followButton.frame = CGRectMake(230, 18, 80, 30);
	
    UIImage *image = [UIImage imageNamed:@"deleteButton.png"];
    UIImage *imagePressed = [UIImage imageNamed:@"deleteButton_pressed.png"];
    
    [followButton setBackgroundImage:[image stretchableImageWithLeftCapWidth:7 topCapHeight:0] forState:UIControlStateNormal];
    [followButton setBackgroundImage:[imagePressed stretchableImageWithLeftCapWidth:7 topCapHeight:0] forState:UIControlStateHighlighted];
    followButton.titleLabel.font = [UIFont boldSystemFontOfSize:13];
    [followButton addTarget:self action:@selector(friendship:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:followButton];
    //不显示followButton
    followButton.hidden = YES;
    
	self.backgroundColor = [UIColor clearColor];
	
    return self;
}


-(void)dealloc
{
    [user relation];
    [profileImage release];
    [super dealloc];
}


- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

  	//CGContextDrawImage(context, rect, background);
	UIColor* backgroundColor = [UIColor colorWithRed:0.8f green:0.8f blue:0.83f alpha:1.0f];
	[backgroundColor set];
	CGRect backgroundRect = CGRectMake(0, 0, 320, 80);
	CGContextFillRect( context, backgroundRect );
	
	CGContextSetLineWidth( context, 1.0);
    CGContextSetAllowsAntialiasing( context, YES);
    CGContextSetRGBStrokeColor( context, 1.0, 1.0, 1.0, 1.0);
    CGContextBeginPath(context );	
	CGContextMoveToPoint( context, 0, 79);
    CGContextAddLineToPoint( context, 320, 79);
    CGContextStrokePath( context );

    CGContextSetRGBStrokeColor( context, 0.5, 0.5, 0.5, 1.0);
    CGContextBeginPath(context );	
	CGContextMoveToPoint( context, 0, 80);
    CGContextAddLineToPoint( context, 320, 80);
    CGContextStrokePath( context );
	
	
    if (profileImage) {
        float w = profileImage.size.width;
        float h = profileImage.size.height;
        
        CGMutablePathRef path = CGPathCreateMutable();
        
        CGPathMoveToPoint  (path, nil, 10+w, 10+h/2);
        CGPathAddArcToPoint(path, nil, 10+w, 10+h, 10+w/2, 10+h,    8);
        CGPathAddArcToPoint(path, nil, 10,   10+h, 10,     10+ h/2, 8);
        CGPathAddArcToPoint(path, nil, 10,   10,   10+w/2, 10,      8);
        CGPathAddArcToPoint(path, nil, 10+w, 10,   10+w,   10+h/2,  8);
        CGPathCloseSubpath(path);
        
        // Fill rect with drop shadow
        CGContextAddPath(context, path);
//        CGContextSetShadowWithColor(context, CGSizeMake(0, -3), 12, [[UIColor darkGrayColor] CGColor]);
        // Drawing with a white stroke color
        if (profileImage) {
            CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
        }
        else {
            CGContextSetRGBFillColor(context, 0.7, 0.7, 0.7, 1.0);
        }
        CGContextFillPath(context);
        
        // Draw path with 2px pen
        CGContextAddPath(context, path);
        CGContextSetLineWidth(context, 2.0);
        CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 1.0);
        CGContextSetShadowWithColor(context, CGSizeZero, 0, [[UIColor whiteColor] CGColor]);
        CGContextDrawPath(context, kCGPathStroke);
        
        CGContextAddPath(context, path);
        CGContextSaveGState(context);
        CGContextClip(context);
        [profileImage drawAtPoint:CGPointMake(10.0, 10.0)];
        CGContextRestoreGState(context);

        CGPathRelease(path);
    }

    // Name, location and URL
	UIColor* textColor = [UIColor blackColor];
	[textColor set];
    [user.screenName drawInRect:CGRectMake(83, 10, 205, 24) withFont:[UIFont boldSystemFontOfSize:18] lineBreakMode:UILineBreakModeTailTruncation];
    
	int y = 34;
	
	if ( user.phone && [user.phone length] > 0 ) {
		[user.phone drawInRect:CGRectMake(83, y, 217, 18) withFont:[UIFont systemFontOfSize:14]];
		y += 18;
	}
	
}


-(void)setUser:(User*)aUser
{
    user = [aUser retain];
    
    if ( [GuaziAppDelegate getAppDelegate].user.userId == user.userId ) {
        own = YES;
    }
    else {
        own = NO;
    }

    self.profileImage = [self getProfileImage:user.profileImageUrl_s isLarge:true];
    [self setNeedsDisplay];
}


- (void)updateImage:(UIImage*)image
{
    self.profileImage = image;
    [self setNeedsDisplay];
}

- (void)didTouchURL:(id)sender
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    [appDelegate openWebView:user.url];
}


- (void) showFollowButtons
{
    if ( own ) {
        followButton.hidden = YES;
    }
    else {
        if ( [user.relation compare:kUserRelationFollowing]==NSOrderedSame || [user.relation compare:kUserRelationBoth]==NSOrderedSame) {
            [followButton setTitle:@"取消关注" forState:UIControlStateNormal];
            followButton.tag = kCancelButtonTag;
        }
        else {
            //没有关注
            [followButton setTitle:@"加为关注" forState:UIControlStateNormal];
            followButton.tag = kFollowButtonTag;
        }
        followButton.hidden = NO;
    }
}


- (void) friendship:(id)sender
{
    UIButton* button = (UIButton*) sender;
    if ( button.tag == kFollowButtonTag ) {
        //关注
        [UserService createFriendship:user];
        [self showFollowButtons];
        [[[GuaziAppDelegate getAppDelegate] friendsViewController] refreshCreateFriendship:user];
    }
    else if ( button.tag == kSilenceButtonTag ) {
        //默默关注
        [TwitterClient createSilenceFollowingSync:user.userId];
        user.relation = kUserRelationSilence;
        [self showFollowButtons];
        SilenceFolloweeViewController* controller = [[GuaziAppDelegate getAppDelegate] silenceViewController];
        if ( controller ) {
            [controller refreshAddUser:user];
        }
    }
    else if ( button.tag == kCancelButtonTag ) {
        NSString* message = nil;
        if ( [user.relation compare:kUserRelationBoth]==NSOrderedSame || [user.relation compare:kUserRelationFollowing]==NSOrderedSame ) {
            message = [NSString stringWithFormat:@"您已经关注了%@。是否确认取消关注?", user.remarkName];
        }
        else if ( [user.relation compare:kUserRelationSilence]==NSOrderedSame ) {
            message = [NSString stringWithFormat:@"您已经默默关注了%@。是否确认取消默默关注?", user.remarkName];
        }
        else {
            return;
        }
        UIActionSheet* as = [[UIActionSheet alloc] initWithTitle:message 
                                                        delegate:self 
                                               cancelButtonTitle:@"取消" 
                                          destructiveButtonTitle:@"确定" 
                                               otherButtonTitles:nil];
        [as showInView:[GuaziAppDelegate getAppDelegate].tabBarController.view];
        [as release];
    }
}


- (void) actionSheet:(UIActionSheet*)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if ( buttonIndex != 0 ) return;
    
    if ( [user.relation compare:kUserRelationBoth]==NSOrderedSame || [user.relation compare:kUserRelationFollowing]==NSOrderedSame ) {
        //取消关注
        [UserService destroyFriendship:user];
        [[[GuaziAppDelegate getAppDelegate] friendsViewController] refreshDestroyFriendship:user.userId];
    }
    else if ( [user.relation compare:kUserRelationSilence]==NSOrderedSame ) {
        [TwitterClient destroySilenceFollowingSync:user.userId];
        SilenceFolloweeViewController* controller = [[GuaziAppDelegate getAppDelegate] silenceViewController];
        if ( controller ) {
            [controller refreshDeleteUser:user.userId];
        }
    }
    
    [self showFollowButtons];
}

@end
